package cn.wolfcode.rbac.servicesImpl;

import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.mapper.RoleMapper;
import cn.wolfcode.rbac.service.RoleService;
import cn.wolfcode.rbac.util.PageResult;
import cn.wolfcode.rbac.util.QueryObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public void delete(long id) {
        roleMapper.deleteById(id);
        roleMapper.deleteRoleAndPermissionRelation(id);
        employeeMapper.deleteEmployeeAndRoleRelationByRoleId(id);
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectList(null);
    }

    @Override
    public void saveOrUpdate(Role role,Long[] ids) {
        if(role.getId() == null){
            roleMapper.insert(role);
        }else{
            roleMapper.updateById(role);
            roleMapper.deleteRoleAndPermissionRelation(role.getId());
        }
        if(ids !=null){
            for (Long permissionId : ids) {
                roleMapper.insertRoleAndPermissionRelation(role.getId(),permissionId);
            }
        }

    }

    @Override
    public PageResult query(QueryObject qo) {
        int row = roleMapper.selectForCount(qo);
        if(row == 0){
            return new PageResult();
        }
        List<Role> data = roleMapper.selectForList(qo);
        return new PageResult(qo.getCurrentPage(),qo.getPageSize(),data,row);
    }
}
